package swingUI;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;


import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;

import com.trsjh.db.controller.Home;
import com.trsjh.db.domains.Customer;
import com.trsjh.db.domains.CustomerAccount;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import mySwingToolkit.ui.ButtonTabComponent;

public class CustomerAccountUI extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5964423659908686078L;
	private com.trsjh.db.domains.CustomerAccount customerAccount = new com.trsjh.db.domains.CustomerAccount();
	private JTextField emailJTextField;
	private JTextField loginNameJTextField;
	private JTextField nameJTextField;
	private JTextPane noteJTextPane;
	private JPasswordField passwordField;
	private JTextField telJTextField;
	private JTextField mainAccountField;
	private JTextField birthdayTextField;
	private JPasswordField passwordField2;
	private JComboBox sexComboBox;
	private JButton saveButton;
	public CustomerAccountUI(
			com.trsjh.db.domains.CustomerAccount newCustomerAccount) {
		this();
		setCustomerAccount(newCustomerAccount);
	}

	public CustomerAccountUI() {
		GridBagLayout gridBagLayout = new GridBagLayout();
		gridBagLayout.columnWidths = new int[] { 0, 0, 0, 0 };
		gridBagLayout.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
		gridBagLayout.columnWeights = new double[] { 0.0, 1.0, 0.0, 1.0E-4 };
		gridBagLayout.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
				1.0E-4 };
		setLayout(gridBagLayout);

		JLabel label_1 = new JLabel("添加新用户");
		GridBagConstraints gbc_label_1 = new GridBagConstraints();
		gbc_label_1.insets = new Insets(0, 0, 5, 5);
		gbc_label_1.gridx = 1;
		gbc_label_1.gridy = 0;
		add(label_1, gbc_label_1);

		JLabel label_2 = new JLabel("<html>主账号<font color=Red>(*)</font></html>");
		GridBagConstraints gbc_label_2 = new GridBagConstraints();
		gbc_label_2.fill = GridBagConstraints.VERTICAL;
		gbc_label_2.insets = new Insets(0, 0, 5, 5);
		gbc_label_2.gridx = 0;
		gbc_label_2.gridy = 1;
		add(label_2, gbc_label_2);

		mainAccountField = new JTextField();
		
		DocumentListener d=new DocumentListener(){
			@Override
			public void changedUpdate(DocumentEvent e) {
			}
			@Override
			public void insertUpdate(DocumentEvent e) {	
				saveButton.setEnabled(false);
			}
			@Override
			public void removeUpdate(DocumentEvent e) {	
				saveButton.setEnabled(false);
			}
		};
		mainAccountField.getDocument().addDocumentListener(d);
		GridBagConstraints gbc_mainAccountField = new GridBagConstraints();
		gbc_mainAccountField.insets = new Insets(0, 0, 5, 5);
		gbc_mainAccountField.fill = GridBagConstraints.HORIZONTAL;
		gbc_mainAccountField.gridx = 1;
		gbc_mainAccountField.gridy = 1;
		add(mainAccountField, gbc_mainAccountField);
		mainAccountField.setColumns(10);

		JLabel loginNameLabel = new JLabel("登录名");
		GridBagConstraints labelGbc_1 = new GridBagConstraints();
		labelGbc_1.insets = new Insets(5, 5, 5, 5);
		labelGbc_1.gridx = 0;
		labelGbc_1.gridy = 2;
		add(loginNameLabel, labelGbc_1);

		loginNameJTextField = new JTextField();
		GridBagConstraints componentGbc_1 = new GridBagConstraints();
		componentGbc_1.insets = new Insets(5, 0, 5, 5);
		componentGbc_1.fill = GridBagConstraints.HORIZONTAL;
		componentGbc_1.gridx = 1;
		componentGbc_1.gridy = 2;
		add(loginNameJTextField, componentGbc_1);
		loginNameJTextField.getDocument().addDocumentListener(d);
		
		JLabel label_6 = new JLabel("默认将与姓名相同");
		GridBagConstraints gbc_label_6 = new GridBagConstraints();
		gbc_label_6.insets = new Insets(0, 0, 5, 0);
		gbc_label_6.gridx = 2;
		gbc_label_6.gridy = 2;
		add(label_6, gbc_label_6);

		JLabel nameLabel = new JLabel("<html>姓名<font color=Red>(*)</font></html>");
		GridBagConstraints labelGbc_2 = new GridBagConstraints();
		labelGbc_2.fill = GridBagConstraints.VERTICAL;
		labelGbc_2.insets = new Insets(5, 5, 5, 5);
		labelGbc_2.gridx = 0;
		labelGbc_2.gridy = 3;
		add(nameLabel, labelGbc_2);

		nameJTextField = new JTextField();
		GridBagConstraints componentGbc_2 = new GridBagConstraints();
		componentGbc_2.insets = new Insets(5, 0, 5, 5);
		componentGbc_2.fill = GridBagConstraints.HORIZONTAL;
		componentGbc_2.gridx = 1;
		componentGbc_2.gridy = 3;
		add(nameJTextField, componentGbc_2);
		nameJTextField.getDocument().addDocumentListener(d);

		JLabel passwordLabel = new JLabel("密码");
		GridBagConstraints labelGbc_4 = new GridBagConstraints();
		labelGbc_4.insets = new Insets(5, 5, 5, 5);
		labelGbc_4.gridx = 0;
		labelGbc_4.gridy = 4;
		add(passwordLabel, labelGbc_4);

		passwordField = new JPasswordField();
		passwordField.setToolTipText("默认888888，电话等敏感信息必须通过密码才能查询，以保障隐私。");
		GridBagConstraints gbc_passwordField = new GridBagConstraints();
		gbc_passwordField.insets = new Insets(5, 0, 5, 5);
		gbc_passwordField.fill = GridBagConstraints.HORIZONTAL;
		gbc_passwordField.gridx = 1;
		gbc_passwordField.gridy = 4;
		add(passwordField, gbc_passwordField);

		JLabel label_7 = new JLabel("查询电话邮箱使用");
		label_7.setToolTipText("");
		GridBagConstraints gbc_label_7 = new GridBagConstraints();
		gbc_label_7.insets = new Insets(0, 0, 5, 0);
		gbc_label_7.gridx = 2;
		gbc_label_7.gridy = 4;
		add(label_7, gbc_label_7);

		JLabel label = new JLabel("再次输入密码");
		GridBagConstraints gbc_label = new GridBagConstraints();
		gbc_label.anchor = GridBagConstraints.EAST;
		gbc_label.insets = new Insets(0, 0, 5, 5);
		gbc_label.gridx = 0;
		gbc_label.gridy = 5;
		add(label, gbc_label);

		passwordField2 = new JPasswordField();
		GridBagConstraints gbc_passwordField2 = new GridBagConstraints();
		gbc_passwordField2.insets = new Insets(0, 0, 5, 5);
		gbc_passwordField2.fill = GridBagConstraints.HORIZONTAL;
		gbc_passwordField2.gridx = 1;
		gbc_passwordField2.gridy = 5;
		add(passwordField2, gbc_passwordField2);

		JLabel telLabel = new JLabel("联系电话");
		GridBagConstraints labelGbc_5 = new GridBagConstraints();
		labelGbc_5.insets = new Insets(5, 5, 5, 5);
		labelGbc_5.gridx = 0;
		labelGbc_5.gridy = 6;
		add(telLabel, labelGbc_5);

		telJTextField = new JTextField();
		GridBagConstraints componentGbc_5 = new GridBagConstraints();
		componentGbc_5.insets = new Insets(5, 0, 5, 5);
		componentGbc_5.fill = GridBagConstraints.HORIZONTAL;
		componentGbc_5.gridx = 1;
		componentGbc_5.gridy = 6;
		add(telJTextField, componentGbc_5);

		JLabel emailLabel = new JLabel("联系邮箱");
		GridBagConstraints labelGbc_0 = new GridBagConstraints();
		labelGbc_0.insets = new Insets(5, 5, 5, 5);
		labelGbc_0.gridx = 0;
		labelGbc_0.gridy = 7;
		add(emailLabel, labelGbc_0);

		emailJTextField = new JTextField();
		GridBagConstraints componentGbc_0 = new GridBagConstraints();
		componentGbc_0.insets = new Insets(5, 0, 5, 5);
		componentGbc_0.fill = GridBagConstraints.HORIZONTAL;
		componentGbc_0.gridx = 1;
		componentGbc_0.gridy = 7;
		add(emailJTextField, componentGbc_0);

		JLabel label_4 = new JLabel("性别");
		GridBagConstraints gbc_label_4 = new GridBagConstraints();
		gbc_label_4.insets = new Insets(0, 0, 5, 5);
		gbc_label_4.gridx = 0;
		gbc_label_4.gridy = 8;
		add(label_4, gbc_label_4);

		sexComboBox = new JComboBox();
		sexComboBox.setModel(new DefaultComboBoxModel(new String[] {"男", "女"}));
		GridBagConstraints gbc_sexComboBox = new GridBagConstraints();
		gbc_sexComboBox.insets = new Insets(0, 0, 5, 5);
		gbc_sexComboBox.fill = GridBagConstraints.HORIZONTAL;
		gbc_sexComboBox.gridx = 1;
		gbc_sexComboBox.gridy = 8;
		add(sexComboBox, gbc_sexComboBox);

		JLabel label_3 = new JLabel("生日");
		GridBagConstraints gbc_label_3 = new GridBagConstraints();
		gbc_label_3.insets = new Insets(0, 0, 5, 5);
		gbc_label_3.gridx = 0;
		gbc_label_3.gridy = 9;
		add(label_3, gbc_label_3);

		birthdayTextField = new JTextField();
		GridBagConstraints gbc_birthdayTextField = new GridBagConstraints();
		gbc_birthdayTextField.insets = new Insets(0, 0, 5, 5);
		gbc_birthdayTextField.fill = GridBagConstraints.HORIZONTAL;
		gbc_birthdayTextField.gridx = 1;
		gbc_birthdayTextField.gridy = 9;
		add(birthdayTextField, gbc_birthdayTextField);
		birthdayTextField.setColumns(10);

		JLabel label_5 = new JLabel("格式：2012-01-01");
		GridBagConstraints gbc_label_5 = new GridBagConstraints();
		gbc_label_5.insets = new Insets(0, 0, 5, 0);
		gbc_label_5.gridx = 2;
		gbc_label_5.gridy = 9;
		add(label_5, gbc_label_5);

		JLabel noteLabel = new JLabel("子账号备注");
		GridBagConstraints labelGbc_3 = new GridBagConstraints();
		labelGbc_3.insets = new Insets(5, 5, 5, 5);
		labelGbc_3.gridx = 0;
		labelGbc_3.gridy = 10;
		add(noteLabel, labelGbc_3);

		noteJTextPane = new JTextPane();
		GridBagConstraints componentGbc_3 = new GridBagConstraints();
		componentGbc_3.insets = new Insets(5, 0, 5, 5);
		componentGbc_3.fill = GridBagConstraints.HORIZONTAL;
		componentGbc_3.gridx = 1;
		componentGbc_3.gridy = 10;
		add(noteJTextPane, componentGbc_3);

		saveButton = new JButton("保存");
		saveButton.setEnabled(false);
		saveButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				saveUser();
			}
		});
		
		JButton mainCheck = new JButton("查询是否存在");
		mainCheck.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				checkMainAccount();
			}
		});
		GridBagConstraints gbc_mainCheck = new GridBagConstraints();
		gbc_mainCheck.insets = new Insets(0, 0, 0, 5);
		gbc_mainCheck.gridx = 0;
		gbc_mainCheck.gridy = 11;
		add(mainCheck, gbc_mainCheck);
		GridBagConstraints gbc_saveButton = new GridBagConstraints();
		gbc_saveButton.insets = new Insets(0, 0, 0, 5);
		gbc_saveButton.gridx = 1;
		gbc_saveButton.gridy = 11;
		add(saveButton, gbc_saveButton);

		JButton clearButton = new JButton("重置");
		clearButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				clearTable();
			}
		});
		GridBagConstraints gbc_clearButton = new GridBagConstraints();
		gbc_clearButton.gridx = 2;
		gbc_clearButton.gridy = 11;
		add(clearButton, gbc_clearButton);


	}
	/**
	 * 清空表单
	 */
	protected void clearTable() {
		this.mainAccountField.setText("");
		this.loginNameJTextField.setText("");
		this.nameJTextField.setText("");
		this.passwordField.setText("");
		this.passwordField2.setText("");
		this.birthdayTextField.setText("");
		this.emailJTextField.setText("");
		this.noteJTextPane.setText("");
		this.telJTextField.setText("");
		this.sexComboBox.setSelectedIndex(0);
	}
	/**
	 * 保存用户
	 */
	protected void saveUser() {
		CustomerAccount ca=new CustomerAccount();
		if(this.mainAccountField.getText().trim().equals("")){
			JOptionPane.showMessageDialog(this, "主账号必须填写");
			return;
		}
		String loginName=this.loginNameJTextField.getText().trim();
		String name=this.nameJTextField.getText().trim();
		if(loginName.equals("")&&name.equals("")){
			JOptionPane.showMessageDialog(this, "请填写姓名");
			return;
		}
		if(loginName.equals("")){
			ca.setLoginName(name);
			ca.setName(name);
		}
		else if(name.equals("")){
			ca.setLoginName(loginName);
			ca.setName(loginName);
		}else{
			ca.setLoginName(loginName);
			ca.setName(name);
		}
		String password=new String(this.passwordField.getPassword());
		String password2=new String(this.passwordField2.getPassword());
		if(password.equals(password2)){
			if(password.equals(""))
				ca.setPassword("888888");
			else
				ca.setPassword(password);
		}else{
			JOptionPane.showMessageDialog(this, "两次密码不相同");
			return;
		}
		if(!this.telJTextField.getText().trim().equals("")){
			ca.setTel(this.telJTextField.getText().trim());
			boolean b=checkPhone(this.telJTextField.getText().trim());
			if(!b){
				return;
			}
		}
		if(!this.emailJTextField.getText().trim().equals("")){
			if(checkEmail(this.emailJTextField.getText().trim())){
				ca.setEmail(this.emailJTextField.getText().trim());
			}else{
				JOptionPane.showMessageDialog(this, "邮箱格式错误");
				return;
			}
		}
		if(!birthdayTextField.getText().trim().equals("")){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			try{
				Date date=sdf.parse(birthdayTextField.getText().trim());
				ca.setBirthday(date);
			}
			catch(Exception ex){
				JOptionPane.showMessageDialog(this, "生日格式错误");
				return;
			} 
		}
		if(!this.noteJTextPane.getText().trim().equals("")){
			ca.setNote(this.noteJTextPane.getText().trim());
		}
		ca.setSex((((String)this.sexComboBox.getSelectedItem()).equals("男"))?'m':'f');
		ca.setRegisterTime(new Date());
		boolean b=checkPhone(this.mainAccountField.getText().trim());		
		if(!b){
			return;
		}
		Home home =new Home();
		Map<Integer,Object> params=new HashMap<Integer,Object>(); 
		params.put(1, this.mainAccountField.getText().trim());
		try{
			Customer customer=(Customer) home.getFirst(Home.GET_CUSTOMERS_BY_PHONE, params);
			home.beginTransaction();
			if(customer==null){
				customer=new Customer(this.mainAccountField.getText().trim());
				home.persist(customer);		
			}
			ca.setCustomer(customer);
			home.persist(ca);
			home.commit();
		}catch(Exception e){
			JOptionPane.showMessageDialog(this, "错误"+e.getMessage());
			home.rollBack();
			return;
		}finally{
			home.closeEntityManager();
		}
		JOptionPane.showMessageDialog(this, "保存成功");
		CustomerRecordViewUI crUI=new CustomerRecordViewUI(ca);
		JTabbedPane tabbedPane =((JTabbedPane)(this.getParent()));
		tabbedPane.add(App.TAB_CUSTOMERRECORDS,crUI);
		tabbedPane.setSelectedComponent(crUI);
		tabbedPane.setTabComponentAt(tabbedPane.indexOfComponent(crUI),new ButtonTabComponent(tabbedPane));
	}
	/**
	 * 检查主账号
	 */
	@SuppressWarnings("unchecked")
	protected int checkMainAccount() {
		String main=this.mainAccountField.getText().trim();
		String name=this.nameJTextField.getText().trim();
		String loginName=this.loginNameJTextField.getText().trim();
		if(main.equals("")){
			JOptionPane.showMessageDialog(this, "主账号不能为空");
			return JOptionPane.CANCEL_OPTION;
		}
		if(name.equals("")&&loginName.equals("")){
			JOptionPane.showMessageDialog(this, "姓名或者登录名不能都为空");
			return JOptionPane.CANCEL_OPTION;
		}
		Home home =new Home();
		if(name.equals("")){
			name=loginName;
		}
		List<CustomerAccount> cas=null;
		Map<Integer,Object> params=new HashMap<Integer,Object>();
		params.put(1, main);
		params.put(2, name);
		cas=home.list(Home.GET_CUSTOMER_BY_PHONE_AND_NAME, params);
		if(cas.size()==0){
			JOptionPane.showMessageDialog(this, "新账号，可以添加！");
			this.saveButton.setEnabled(true);
		}else{
			JOptionPane.showMessageDialog(this, "账号已经存在！");
			return JOptionPane.NO_OPTION;
		}
		return JOptionPane.YES_OPTION;
//		JOptionPane.showMessageDialog(this, "");
//		return 0;

	}


	public CustomerAccountUI(String phone, String name) {
		this();
		this.mainAccountField.setText(phone);
		this.nameJTextField.setText(name);
		if(!phone.equals("")&&!name.equals("")){
			this.saveButton.setEnabled(true);
		}
	}

	public com.trsjh.db.domains.CustomerAccount getCustomerAccount() {
		return customerAccount;
	}

	public void setCustomerAccount(
			com.trsjh.db.domains.CustomerAccount newCustomerAccount) {
		setCustomerAccount(newCustomerAccount, true);
	}

	public void setCustomerAccount(
			com.trsjh.db.domains.CustomerAccount newCustomerAccount,
			boolean update) {
	}
	public static boolean checkPhone(String phone){
		if(phone.length()!=8&&phone.length()<11){
			int i= JOptionPane.showConfirmDialog(null, "号码可能有误，请确认号码："+phone, "提示", JOptionPane.YES_NO_OPTION);
			if(i==JOptionPane.YES_OPTION){
				return true;
			}else{
				return false;
			}
		}else{
			Pattern p=Pattern.compile("[\\d-]+");
			Matcher m=p.matcher(phone);
			if(m.matches()){
				return true;
			}else{
				return false;
			}
		}
	}
	public static boolean checkEmail(String email){
		boolean isExist = false;

		Pattern p = Pattern.compile("^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
		Matcher m = p.matcher(email);
		boolean b = m.matches();
		if(b) {
			System.out.println("有效邮件地址");
			isExist=true;
		} else {
			System.out.println("无效邮件地址");
		}
		return isExist;
	}

}
